package com.bii.gelapp;

import java.io.ByteArrayOutputStream;

import org.opencv.android.Utils;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.core.Scalar;
import org.opencv.core.Size;
import org.opencv.imgproc.Imgproc;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;

public class GaborActivity extends Activity {
	ImageView ivImage;
	public Bitmap originalBmp; // origin
	public Bitmap activeBmp; // edited image
	public Bitmap takenBmp;
	Button btPrev, btSegment, btSave, btFilter;
	TextView tvThreshold;
	SeekBar sbThreshold;

	int kernelSize = 24;
	double sigma = 8;
	double theta = Math.PI / 2;
	double lambda = 21;
	double gamma = 1;
	double psi = 1.5;

	public static int currentprogress;
	int thresholdvalue;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.gaboractivity);
		ivImage = (ImageView) findViewById(R.id.ivImage);
		byte[] byteArray = getIntent().getByteArrayExtra("BMP");
		originalBmp = BitmapFactory.decodeByteArray(byteArray, 0,
				byteArray.length);
		Bitmap resizedbmp = Bitmap.createScaledBitmap(originalBmp, 300, 300,
				true);
		ivImage.setImageBitmap(resizedbmp);
		btPrev = (Button) findViewById(R.id.btPrev);
		btSegment = (Button) findViewById(R.id.btSegment);
		btSave = (Button) findViewById(R.id.btSave);
		btFilter = (Button) findViewById(R.id.btFilter);
		tvThreshold = (TextView) findViewById(R.id.tvThreshold);
		sbThreshold = (SeekBar) findViewById(R.id.sbThreshold);
		// apply gabor before threshold
		sbThreshold.setEnabled(false);
		btPrev.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				startActivity(new Intent(GaborActivity.this,
						GaussianActivity.class));

			}
		});
		btSegment.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent goToNextActivity = new Intent(getApplicationContext(),
						SegmentationActivity.class);
				byte[] bytes;
				if (activeBmp == null) {
					bytes = compressImage(originalBmp);
				} else {
					bytes = compressImage(activeBmp);
				}
				goToNextActivity.putExtra("BMP", bytes);
				startActivity(goToNextActivity);

			}
		});

		btFilter.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// convert to mat
				Mat filtermat = new Mat(originalBmp.getHeight(), originalBmp
						.getWidth(), CvType.CV_8U);
				int ch= filtermat.channels();
				//Bitmap myBitmap32 = originalBmp.copy(Bitmap.Config.RGB_565,
				//		true);
				Utils.bitmapToMat(originalBmp, filtermat);
				Imgproc.cvtColor(filtermat, filtermat, Imgproc.COLOR_BGR2GRAY);
				
				ch= filtermat.channels();
				// result image below
				Mat resultImg = new Mat();
				// set gabor
				Mat gaborKernel = Imgproc.getGaborKernel(new Size(kernelSize,
						kernelSize), sigma, theta/* horizontal */, lambda,
						gamma, psi, CvType.CV_32F);
				/*
				Mat displayGaborKernel = gaborKernel.clone();
				for (int i = 0; i < displayGaborKernel.height(); i++) {
					for (int j = 0; j < displayGaborKernel.width(); j++) {
						double[] data = displayGaborKernel.get(i, j);
						data[0] = (1 + data[0]) * 127.5;
						displayGaborKernel.put(i, j, data);
					}
				}*/
				ch= filtermat.channels();
				Imgproc.filter2D(filtermat, resultImg, -1, gaborKernel);
				// convert result img into bitmap, then copy it to activebmp
				
				//Bitmap filteredBmp = Bitmap.createBitmap(resultImg.cols(),
				//resultImg.rows(), Bitmap.Config.ARGB_8888);
				//Utils.matToBitmap(resultImg, filteredBmp);
				
				ch= resultImg.channels();
				
				// gray scale
				//Mat grayImg = new Mat();
				//Imgproc.cvtColor(resultImg, grayImg, Imgproc.COLOR_BGR2GRAY);
				//Bitmap filteredBmp = Bitmap.createBitmap(grayImg.cols(),
				//		grayImg.rows(), Bitmap.Config.RGB_565);

				// convert mat back to bitmap set active bmp to gray scale
				//Utils.matToBitmap(grayImg, filteredBmp);
				
				Bitmap filteredBmp = Bitmap.createBitmap(resultImg.cols(),
				resultImg.rows(), Bitmap.Config.ARGB_8888);
				Utils.matToBitmap(resultImg, filteredBmp);

				activeBmp = filteredBmp;
				// display result
				Bitmap resizedbmp = Bitmap.createScaledBitmap(filteredBmp, 300,
						300, true);
				ivImage.setImageBitmap(resizedbmp);
				// apply gabor before threshold
				sbThreshold.setEnabled(true);
			}
		});

		sbThreshold.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {

			@Override
			public void onStopTrackingTouch(SeekBar seekBar) {

			}

			@Override
			public void onStartTrackingTouch(SeekBar seekBar) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onProgressChanged(SeekBar seekBar, int progress,
					boolean fromUser) {
				if (activeBmp == null) {
					if (takenBmp == null) {
						takenBmp = originalBmp;
					}
				} else {
					if (takenBmp == null) {
						takenBmp = activeBmp;
					}
				}

				currentprogress = sbThreshold.getProgress();
				thresholdvalue = currentprogress;
				if (currentprogress != 0) {
					Mat srcImg = new Mat(takenBmp.getHeight(), takenBmp
							.getWidth(), CvType.CV_8U, new Scalar(4));
					Bitmap myBitmap32 = takenBmp.copy(Bitmap.Config.ARGB_8888,
							true);
					Utils.bitmapToMat(myBitmap32, srcImg);
					Mat thresholdMat = new Mat();
					Imgproc.threshold(srcImg, thresholdMat, thresholdvalue,
							255, Imgproc.THRESH_BINARY);
					Bitmap thBmp = Bitmap.createBitmap(thresholdMat.cols(),
							thresholdMat.rows(), Bitmap.Config.ARGB_8888);
					Utils.matToBitmap(thresholdMat, thBmp);
					Bitmap resizedbmp = Bitmap.createScaledBitmap(thBmp, 300,
							300, true);
					
					ivImage.setImageBitmap(resizedbmp);
					tvThreshold.setText("Threshold: " + currentprogress);
					activeBmp = thBmp;
				} else {
					Bitmap resizedbmp = Bitmap.createScaledBitmap(takenBmp,
							300, 300, true);
					ivImage.setImageBitmap(resizedbmp);
					tvThreshold.setText("Threshold: " + currentprogress);
				}
			}
		});

	}

	public byte[] compressImage(Bitmap image) {
		ByteArrayOutputStream stream = new ByteArrayOutputStream();
		image.compress(Bitmap.CompressFormat.PNG, 0, stream);
		byte[] bytes = stream.toByteArray();
		return bytes;

	}
}
